const log4js = require('log4js');

const logger = log4js.getLogger();
const LOG_LEVEL = process.env.OPTIMUS_LOG_LEVEL || 'INFO';

log4js.addLayout('custom', () => (logEvent) => {
  const logs = logEvent.data;
  let processLogs = [];
  processLogs = logs.map((logItem) => {
    if (typeof logItem === 'string') {
      return logItem.replace(/\n/g, ' ');
    }
    try {
      return process.env.OPTIMUS_ENV === 'local' ? JSON.stringify(logItem, null, 2) : JSON.stringify(logItem);
    } catch (e) {
      return logItem;
    }
  });
  return `[${logEvent.startTime.toISOString()}] [${logEvent.level.levelStr}] - ${processLogs.join(' ')}`;
});

log4js.configure({
  appenders: {
    console: {
      type: 'console',
      layout: {
        type: 'custom',
      },
    },
  },
  categories: { default: { appenders: ['console'], level: LOG_LEVEL } },
});

logger.mark('LOG_LEVEL', LOG_LEVEL);

module.exports = logger;
